<script setup lang="ts">
import { ref } from 'vue'
import { postLoginWxMinAPI, saveUserInfoUsingPost } from '@/services/login'
import { useMemberStore } from '@/stores'

const hasUserInfo = ref(false)
const isAgreed = ref(false) // 用户协议状态
const memberStore = useMemberStore()

// 切换协议状态
const togglePlay = () => {
  isAgreed.value = !isAgreed.value
}

const onGetUserInfo = async (e) => {
  if (!isAgreed.value) {
    await uni.showToast({
      title: '请先同意服务条款和隐私协议',
      icon: 'none',
    })
    return
  }
  console.log('e.detail:', e.detail)
  if (e.detail.userInfo) {
    try {
      // 获取用户登录凭证 code
      const loginRes = await new Promise((resolve, reject) => {
        uni.login({
          success: (res) => resolve(res),
          fail: (err) => reject(err),
        })
      })
      const { code } = loginRes
      console.log('code:', code)
      // 调用后端接口获取 openid，传入 code
      const response = await postLoginWxMinAPI({
        code,
        encryptedData: e.detail.encryptedData,
        iv: e.detail.iv,
      })
      console.log('response:', response)
      const openid = response.data!.openid
      console.log('openid:', openid)
      if (openid) {
        // 存储 openid 和用户信息
        memberStore.setProfileField('openid', openid)
        console.log('openid:', memberStore.profile?.openid)
        memberStore.setProfileField('avatarUrl', e.detail.userInfo.avatarUrl)
        console.log('avatarUrl:', memberStore.profile?.avatarUrl)
        memberStore.setProfileField('nickName', e.detail.userInfo.nickName)
        console.log('nickName:', memberStore.profile?.nickName)
        const { avatarUrl, nickName } = memberStore.profile
        await saveUserInfoUsingPost({ openid, avatarUrl, nickName })
        hasUserInfo.value = true
        // // 页面跳转并刷新
        // setTimeout(() => {
        //   uni.switchTab({
        //     url: '/pages/my/my',
        //     success: () => {
        //       const page = getCurrentPages().find((page) => page.route === 'pages/my/my')
        //       if (page) {
        //         page.onLoad && page.onLoad()
        //       }
        //     },
        //   })
        // }, 500)
        // 返回上一个页面
        uni.showToast({
          title: '登录成功',
          icon: 'success',
          duration: 1500,
        })
        // 获取页面栈并判断上一页面
        const pages = getCurrentPages()
        const prevPage = pages[pages.length - 2] // 获取上一个页面

        const reloadMyPage = () => {
          const page = getCurrentPages().find((page) => page.route === 'pages/my/my')
          if (page) {
            page.onLoad && page.onLoad()
          }
        }

        if (prevPage && prevPage.route === 'pages/my/my') {
          // 如果上一个页面是 'pages/my/my'，跳转到我的页面
          uni.switchTab({
            url: '/pages/my/my',
            success: reloadMyPage,
          })
        } else {
          // 否则返回上一页面
          uni.navigateBack({
            success: reloadMyPage,
          })
        }
      } else {
        throw new Error('未能获取 openid')
      }
    } catch (error) {
      await uni.showToast({
        title: '获取用户信息失败',
        icon: 'none',
      })
      console.error('获取用户信息失败', error)
    }
  } else {
    await uni.showToast({
      title: '用户拒绝授权',
      icon: 'none',
    })
  }
}
</script>

<template>
  <view class="login">
    <view class="logo">
      <image src="@/static/images/LOGO.svg" />
    </view>
    <view class="login">
      <button open-type="getUserInfo" @getuserinfo="onGetUserInfo" class="button weixin">
        <text class="icon icon-weixin"></text>
        微信快捷登录
      </button>
      <view class="extra"></view>

      <view class="tips">
        <label class="agreement-text">
          <uni-icons
            :type="isAgreed ? 'checkbox-filled' : 'checkbox'"
            size="17"
            @tap="togglePlay"
          />
          登录/注册即视为你同意 <a href="#" class="agreement-link">《服务条款》</a> 和
          <a href="#" class="agreement-link">《天门山·智慧导览隐私协议》</a>
        </label>
      </view>
    </view>
  </view>
</template>

<style lang="scss">
.page {
  height: 100%;
}

.login {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20rpx 40rpx;
}

.logo {
  flex: 1;
  text-align: center;

  image {
    width: 300rpx;
    height: 300rpx;
    margin-top: 15vh;
  }
}

.login {
  display: flex;
  flex-direction: column;
  height: 60vh;
  padding: 40rpx 20rpx 20rpx;

  .input {
    width: 100%;
    height: 80rpx;
    font-size: 28rpx;
    border-radius: 72rpx;
    border: 1px solid #ddd;
    padding-left: 30rpx;
    margin-bottom: 20rpx;
  }

  .button {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 80rpx;
    font-size: 28rpx;
    border-radius: 72rpx;
    color: #fff;

    .icon {
      font-size: 40rpx;
      margin-right: 6rpx;
    }
  }

  .weixin {
    background-color: #28bb9c;
  }
  .wechat {
    background-color: #06c05f;
  }

  .extra {
    flex: 1;
    padding: 70rpx 70rpx 0;

    .caption {
      width: 440rpx;
      line-height: 1;
      border-top: 1rpx solid #ddd;
      font-size: 26rpx;
      color: #999;
      position: relative;

      text {
        transform: translate(-40%);
        background-color: #fff;
        position: absolute;
        top: -12rpx;
        left: 50%;
      }
    }

    .options {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 70rpx;

      button {
        padding: 0;
        background-color: transparent;
      }
    }

    .icon {
      font-size: 24rpx;
      color: #444;
      display: flex;
      flex-direction: column;
      align-items: center;

      &::before {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 80rpx;
        height: 80rpx;
        margin-bottom: 6rpx;
        font-size: 40rpx;
        border: 1rpx solid #444;
        border-radius: 50%;
      }
    }

    .icon-weixin::before {
      border-color: #06c05f;
      color: #06c05f;
    }
  }
}

.tips {
  position: absolute;
  bottom: 80rpx;
  left: 20rpx;
  right: 20rpx;
  font-size: 22rpx;
  color: #999;
  text-align: center;
}

.agreement {
  margin-top: 20rpx;
  display: flex;
  align-items: center;

  .checkbox {
    margin-right: 10rpx;
    width: 24rpx;
    height: 24rpx;
    border: 1px solid #28bb9c;
    border-radius: 4rpx;
    position: relative;
    cursor: pointer;
  }

  .checkbox:checked {
    background-color: #28bb9c;
    border-color: #28bb9c;
  }

  .agreement-text {
    font-size: 20rpx;
    color: #666;
  }

  .agreement-link {
    color: #28bb9c;
  }
}
</style>
